// pages/regimental-commander/order/order.js
// const orderList = [{
//   date: '2023-08-24',
//   orders: [{
//     id: 1,
//     // 订单状态 0:待配送, 1: 待提货，2: 已提货，3: 售后
//     status: 0,
//     orderTime: '2023-08-24 15:34:45',
//     userName: '老王',
//     userTel: '13000000000',
//     orderNumber: 'OD-123',
//     pieces: 4,
//     products: [{
//       id: 1,
//       title: '2斤±0.2斤/份【新鲜脆嫩】山东铁杆大葱扒皮去半页',
//       num: 2,
//       payment: 12.2,
//       unitPrice: 6.1,
//       preferential: 0.8,
//       imageURL: '/image/level-icon.png'
//     },{
//       id: 3,
//       title: '2斤±0.2斤/份【新鲜脆嫩】山东铁杆大葱扒皮去半页',
//       num: 1,
//       payment: 12.2,
//       unitPrice: 6.1,
//       preferential: 0.8,
//       imageURL: '/image/level-icon.png'
//     }]
//   }]
// },{
//   date: '2023-08-23',
//   orders: [{
//     id: 4,
//     // 订单状态 0:待配送, 1: 待提货，2: 已提货，3: 售后
//     status: 0,
//     orderTime: '2023-08-24 15:34:45',
//     userName: '老王',
//     userTel: '13000000000',
//     orderNumber: 'OD-123',
//     pieces: 4,
//     products: [{
//       id: 5,
//       title: '2斤±0.2斤/份【新鲜脆嫩】山东铁杆大葱扒皮去半页',
//       num: 2,
//       payment: 12.2,
//       unitPrice: 6.1,
//       preferential: 0.8,
//       imageURL: '/image/level-icon.png'
//     }]
//   },{
//     id: 2,
//     // 订单状态 0:待配送, 1: 待提货，2: 已提货，3: 售后
//     status: 0,
//     orderTime: '2023-08-24 15:34:45',
//     userName: '老王',
//     userTel: '13000000000',
//     orderNumber: 'OD-123',
//     pieces: 4,
//     products: [{
//       id: 2,
//       title: '2斤±0.2斤/份【新鲜脆嫩】山东铁杆大葱扒皮去半页',
//       num: 2,
//       payment: 12.2,
//       preferential: 0.8,
//       imageURL: '/image/level-icon.png'
//     }]
//   }]
// }]

const app = getApp()
import { formatTimes } from '../../../utils/util'
import Dialog from '../../../dist/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderTypes: [
      { type: 'index', text: '全部' },
      { type: 'waitDeliver', text: '待提货' },
      { type: 'completed', text: '已提货' },
      { type: 'waitRefund', text: '售后' }
    ],
    activeOrderType: 'index',
    toBeBtns: [
      { type: 1, text: '今天' },
      { type: 2, text: '昨天' },
      { type: 3, text: '更早之前'}
    ],
    toBeBtnsActive: 1,
    afterSalesBtns: [
      { type: 1, text: '全部' },
      { type: 2, text: '待门店审核' },
      { type: 3, text: '待门店确认退货'}
    ],
    afterSalesActive: 1,
    orderList: [],
    refundBtns: [],
    page:1,
    total:0
  },

  /**
   * 获取订单列表
   */
  getOrderList: function() {
    const orderType = this.data.activeOrderType
    let urlStr = ''
    // 售后列表，需要加子状态
    if (orderType == 'waitRefund') {
      urlStr += `plugin.package-deliver.frontend.order.refund.lists&cate=${this.data.afterSalesActive}&page=${this.data.page}`
    } else {
      urlStr = 'plugin.package-deliver.frontend.order.list.' + orderType + `&page=${this.data.page}`
    }
    // 待提货需要加子状态
    if (orderType == 'waitDeliver') {
      urlStr += `&cate=${this.data.toBeBtnsActive}`
    }
    // 售后需要加子状态
    const url = app.getNetAddresss(urlStr)
    const _this = this
    // this.setData({
    //   orderList: []
    // })
    wx.showLoading({
      title: '加载中',
    })
    app._postNetWork({
      url,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const resList = resData.data.data
          if (resList && resList.length) {
            const dates = resList.map(item => {
              return formatTimes(new Date(item.create_time)) 
            })
            // 数组去重
            const dateArray = Array.from(new Set(dates))
            const orderArray = []
            dateArray.forEach(date => {
              const orders = resList.filter(order => formatTimes(new Date(order.create_time)) == date)
              orderArray.push({
                date,
                orders
              })
            })
            _this.setData({
              orderList: _this.data.orderList.concat(orderArray),
              total:resData.data.total
            })
          }
        } else {
          wx.showToast({ icon: 'none', title: resData.msg })
        }
      },
      complete: function() {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })
  },
 /**
  * 是否确认收货
  *  **/
 orderOperationReceiveConfirm(api,order){
   let that = this
   Dialog.confirm({
    title:"提示",
    selector:'#myDialog',
    context:this,
    message: '是否确认收货?',
  })
    .then(() => {
      this.orderOperationReceive(api,order);
    })
    .catch(() => {
      // on cancel
    });
 },
  /**
  * 是否确认收货
  *  **/
 orderOperationReceive(api,order){
   let that = this
 app._postNetWork({
   url:app.getNetAddresss(api) + '&order_id=' + order.id,
   success: function(res) {
     console.log(res)
     if(res.data.result){
      app.tips('操作成功！');
      that.setData({
        page:1,
        orderList:[]
      })
      that.getOrderList()
     }else{
      app.tips(res.data.msg);
     }
    
   }
 })  
},
  /**
   * 订单状态改变
   * @param {Object} e 
   */
  orderTypeChange: function(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      activeOrderType: type,
      page:1,
      orderList:[]
    })
    this.getOrderList()
  },

  /**
   * 待提货筛选按钮点击
   * @param {Object} e 
   */
  toBeBtnClick: function(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      toBeBtnsActive: type,
      page:1,
      orderList:[]
    })
    this.getOrderList()
  },

  /**
   * 售后筛选按钮点击
   * @param {Object} e 
   */
  afterSalesBtnClick: function(e) {
    const { type } = e.currentTarget.dataset
    this.setData({
      afterSalesActive: type,
      page:1,
      orderList:[]
    })
    this.getOrderList()
  },

  /**
   * 商品申请退款
   * @param {Object} e 
   */
  goApplayRefund: function(e) {
    const {product} = e.currentTarget.dataset
    if(product.order.status == 1) {
      wx.showModal({
        title: '暂不支持申请退款',
        content: '为保障客户体验，在商品到店前，仅支持顾客自行申请退款',
        showCancel: false,
        confirmText: '我知道了',
        confirmColor: '#ee0a24'
      })
      return
    }
    const str = JSON.stringify(product)
    wx.navigateTo({
      url: '/pages/regimental-commander/order-refund/order-refund?params=' + encodeURIComponent(str)
    })
  },

  /**
   * 售后按钮点击
   * @param {Object} e 
   */
  refundBtnClick: function(e) {
    const { order, item } = e.currentTarget.dataset
    this.goCustomRefundDetail(order, item)
  },

  /**
   * 跳转到售后详情
   * @param {Object} e 
   */
  goCustomRefundDetail: function(order, btn) {
    const str = JSON.stringify({order, btn})
    wx.navigateTo({
      url: '/pages/regimental-commander/after-sales-details/after-sales-details?params=' + encodeURIComponent(str)
    })
  },

  /**
   * 分享商品(跳转到首页)
   */
  shareProduct: function() {
    wx.reLaunch({
      url: '/packageG/newDiy/newDiy',
    })
  },
  
  /**
   * 订单按钮点击
   * @param {Object} e 
   */
  orderBtnClick: function(e) {
    const { api, value, order } = e.currentTarget.dataset
    console.log(api, value, order)
    if(value == 'package_deliver'){
      this.orderOperationReceiveConfirm(api,order)
    }
  },

  /**
   * 跳转到售后详情(系统原有)
   * @param {Object} e 
   */
  goRefundDetail: function(e) {
    const { order } = e.currentTarget.dataset
    let _url = '';
    if (order.plugin_id == 40 && order.refund_type == 1 && order.status == 6) {
      _url = "/packageB/member/OrderReturnSure/OrderReturnSure?id=" + order.order.id;
    } else {
      if (order.plugin_id === 144) _url = `/packageF/consumption/refundProcess/refundProcess?refundId=${order.id}`;
      if (order.plugin_id !== 144) _url = "/packageD/member/myOrder/Aftersales/Aftersales?refund_id=" + order.id +"&pluginid=" + order.plugin_id;
    }
    wx.navigateTo({
      url: _url
    });
  },

  /**
   * 复制
   * @param {Object} e 
   */
  copy: function(e) {
    const content = String(e.currentTarget.dataset.copyContent)
    wx.setClipboardData({
      data: content,
    })
  },

  /**
   * 拨打电话
   * @param {Object} e 
   */
  call: function(e) {
    const tel = String(e.currentTarget.dataset.tel)
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置默认订单类型
    if (options) {
      const { orderType } = options
      if (orderType) {
        this.setData({
          activeOrderType: orderType
        })
      }
    }
    this.getOrderList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page:1,
      orderList:[]
    })
    this.getOrderList()
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.page*20 >= this.data.total){
      return false
    }
    this.setData({
      page:this.data.page+1
    })
    this.getOrderList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})